package com.jichaoyun.sys.service.impl;


import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.MapUtils;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jichaoyun.common.enums.MyExceptiontType;
import com.jichaoyun.common.ex.MyException;
import com.jichaoyun.common.utils.ExcelStyleUtils;
import com.jichaoyun.model.entity.Valve;
import com.jichaoyun.model.entity.User;
import com.jichaoyun.model.entity.ValveAlarm;
import com.jichaoyun.sys.mapper.UserMapper;
import com.jichaoyun.sys.mapper.ValveAlarmMapper;
import com.jichaoyun.sys.mapper.ValveMapper;
import com.jichaoyun.sys.service.ValveAlarmService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ValveAlarmServiceImpl extends ServiceImpl<ValveAlarmMapper, ValveAlarm> implements ValveAlarmService {

    @Autowired
    private ValveAlarmMapper valveAlarmMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ValveMapper valveMapper;

    /**
     * 阀门报警信息已读接口
     * @param userId
     */
    @Override
    public void MakeAlarmRead(Integer id,Integer userId) {
        LambdaQueryWrapper<User> queryWrapper0 = new LambdaQueryWrapper<>();
        queryWrapper0.eq(User::getId,userId);
        User user = this.userMapper.selectOne(queryWrapper0);

        if(user.getUserRole() != 0){
            LambdaQueryWrapper<ValveAlarm> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ValveAlarm::getValveId,id);
            ValveAlarm valveAlarm = this.valveAlarmMapper.selectOne(wrapper);
            valveAlarm.setIsReadAdmin(true);
            this.valveAlarmMapper.updateById(valveAlarm);
        }else {
            LambdaQueryWrapper<ValveAlarm> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ValveAlarm::getValveId,id);
            ValveAlarm valveAlarm = this.valveAlarmMapper.selectOne(wrapper);
            valveAlarm.setIsRead(true);
            this.valveAlarmMapper.updateById(valveAlarm);
        }

    }
    /**
     * 全部阀门报警信息已读接口
     * @param userId
     */
    @Override
    public void MakeAlarmRead(Integer userId) {
        
        LambdaQueryWrapper<User> queryWrapper0 = new LambdaQueryWrapper<>();
        queryWrapper0.eq(User::getId,userId);
        User user = this.userMapper.selectOne(queryWrapper0);
        if(user.getUserRole() != 0){

                LambdaQueryWrapper<ValveAlarm> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(ValveAlarm::getIsReadAdmin,0);
                List<ValveAlarm> ValveAlarmList = this.valveAlarmMapper.selectList(lambdaQueryWrapper);

                for(ValveAlarm valveAlarm:ValveAlarmList){
                    valveAlarm.setIsReadAdmin(true);
                    this.valveAlarmMapper.updateById(valveAlarm);
                }
        }else {
            LambdaQueryWrapper<Valve> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Valve::getUserName,user.getUsername());
            List<Valve> ValveList = this.valveMapper.selectList(queryWrapper);

            List<Integer> valveNoList = new ArrayList<>();
            for(Valve valve:ValveList){
                valveNoList.add(valve.getValveId());
            }

            if(valveNoList.isEmpty()){
                throw new MyException(MyExceptiontType.Other,null);
            }

                LambdaQueryWrapper<ValveAlarm> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.in(ValveAlarm::getValveId,valveNoList)
                        .eq(ValveAlarm::getIsRead,0);
                List<ValveAlarm> ValveAlarmList = this.valveAlarmMapper.selectList(lambdaQueryWrapper);

                for(ValveAlarm valveAlarm:ValveAlarmList){
                    valveAlarm.setIsRead(true);
                    this.valveAlarmMapper.updateById(valveAlarm);
                }
        }
    }
    /**
     * 查询未读的阀门报警信息
     * @return
     */
    @Override
    public List<Map<String,Object>> pollingDb(Integer userId) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getId,userId);
        User user = this.userMapper.selectOne(queryWrapper);
        if(user.getUserRole() != 0){
            //查询所有未读的报警
            LambdaQueryWrapper<ValveAlarm> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ValveAlarm::getIsReadAdmin,0).orderByAsc(ValveAlarm::getId);
            List<ValveAlarm> list = valveAlarmMapper.selectList(wrapper);

            if(list != null){
                List<Map<String,Object>> resList = new ArrayList<>();

                Map<String,Object> map1 = new HashMap<>();
                Map<String,Integer> map2 = new HashMap<>();
                for(ValveAlarm item:list){
                    //一个阀门的报警只取最新的一条
                    map1.put(item.getVName(),item.getVStartTime().toString());
                    map2.put(item.getVName(),item.getId());
                }
                for(String item : map1.keySet()){
                    Map<String, Object> map = new HashMap<>();
                    map.put("报警类型","阀门报警");
                    map.put("报警阀门",item);
                    map.put("报警时间",map1.get(item));
                    map.put("id",map2.get(item));
                    resList.add(map);
                }
                return resList;
            }
        }else {
            List<Map<String,Object>> resList = new ArrayList<>();

            LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userLambdaQueryWrapper.eq(User::getId,userId);
            User res = this.userMapper.selectOne(userLambdaQueryWrapper);
            LambdaQueryWrapper<Valve> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(Valve::getUserName,res.getUsername());
            List<Valve> valveList = this.valveMapper.selectList(queryWrapper1);

            List<Integer> valveNoList = new ArrayList<>();
            for(Valve valve:valveList){
                valveNoList.add(valve.getValveId());
            }

            if(valveNoList.isEmpty()){
                return resList;
            }
            //查询所有未读的报警
            LambdaQueryWrapper<ValveAlarm> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ValveAlarm::getIsRead,0)
                    .in(ValveAlarm::getValveId,valveNoList)
                    .orderByAsc(ValveAlarm::getId);
            List<ValveAlarm> list = valveAlarmMapper.selectList(wrapper);

            if(list != null){


                Map<String,Object> map1 = new HashMap<>();
                Map<String,Integer> map2 = new HashMap<>();
                for(ValveAlarm item:list){
                    //一个阀门的报警只取最新的一条
                    map1.put(item.getVName(),item.getVStartTime().toString());
                    map2.put(item.getVName(),item.getId());
                }
                for(String item : map1.keySet()){
                    Map<String, Object> map = new HashMap<>();
                    map.put("报警类型","阀门报警");
                    map.put("报警阀门",item);
                    map.put("报警时间",map1.get(item));
                    map.put("id",map2.get(item));
                    resList.add(map);
                }
                return resList;
            }
        }

        return null;
    }

    /**
     * 分页获取阀门报警信息
     * @return
     */
    @Override
    public IPage<ValveAlarm> getValveAlarm(Integer pageNo, Integer pageSize) {
        IPage<ValveAlarm> valveIPage = new Page<>(pageNo,pageSize);
        QueryWrapper<ValveAlarm> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("valve_id");
        return this.valveAlarmMapper.selectPage(valveIPage,queryWrapper);
    }

    /**
     * 导出报警信息数据到excel
     * @param response
     * @throws IOException
     */
    @Override
    public void getValveAlarmExcel(HttpServletResponse response) throws IOException {
        LambdaQueryWrapper<ValveAlarm> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.orderByAsc(ValveAlarm::getValveId);
        List<ValveAlarm> valveAlarmList = this.valveAlarmMapper.selectList(lambdaQueryWrapper);

        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("阀门报警信息表", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(ExcelStyleUtils.getHeadStyle(), ExcelStyleUtils.getContentStyle());

            // 这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream(), ValveAlarm.class)
                    .registerWriteHandler(horizontalCellStyleStrategy)
                    .autoCloseStream(Boolean.FALSE)
                    .sheet("sheet1")
                    .doWrite(valveAlarmList);

        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = MapUtils.newHashMap();
            map.put("status", "failure");

            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSONUtils.toJSONString(map));
            throw new MyException(MyExceptiontType.FILEDOWNLOADFAIL,"下载文件失败");
        }
    }
}
